package com.zl.sso.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.store.redis.RedisTokenStore;

/**
 * 授权服务配置类
 * 作者：周浪
 * 时间：2021-11-9
 */
@Configuration
@EnableAuthorizationServer
public class AuthorizationServiceConfig  extends AuthorizationServerConfigurerAdapter {

    @Autowired
    private AuthenticationManager authenticationManager;//认证管理器

    @Autowired
    private RedisConnectionFactory redisConnectionFactory;//注入redis存放信息

    @Autowired
    private UserDetailsService userDetailsService;//用户信息

    public AuthorizationServiceConfig() {
        super();
    }

    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
        //允许客户端表单验证
        security.allowFormAuthenticationForClients();
    }

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.inMemory()
                //这个好比账号
                .withClient("client_id")
                //授权的类型
                .authorizedGrantTypes("password","refresh_token")
                //有效时间
                .accessTokenValiditySeconds(1800)
                .refreshTokenValiditySeconds(60*60*2)
                .resourceIds("rid")
                //范围
                .secret("all")
                //密码
                .secret("$2a$10$RMuFXGQ5AtH4wOvkUgyvuecpqUSeoxZYqi1Xzbz5edceRsga.WYiq");
    }

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        endpoints.tokenStore(new RedisTokenStore(redisConnectionFactory))
                //身份认证管理
                .authenticationManager(authenticationManager)
                .userDetailsService(userDetailsService);
    }
}
